library(readxl)
library(Matching)
library(tableone)
library(dplyr)
library(openxlsx)
#无形资产/x1	资产负债率/x2	总资产报酬率ROA/x3	现金流状况/x4	财务杠杆率/x5

zcz <- read_excel("注册制_控制变量_normalized.xlsx") 
shz <- read_excel("核准制_控制变量_normalized.xlsx") 

#匹配2018年的数据
zcz_2018 <- zcz[zcz$Time == 2018, ]
shz_2018 <- shz[shz$Time == 2018, ]

rawdata <- rbind(zcz_2018,shz_2018)

fit1<- glm(Y ~ x1 + x2 + x3 + x4 + x5, 
           data=rawdata,
           family=binomial(link = "logit"),
           control=list(maxit=100))
X <- fit1$fitted
Tr<- (rawdata$Y == 1)
rr1  <- Match(Tr=Tr, X=X, M=1,replace  = FALSE)#Y不设置也可以
bcMatched2<- rawdata[unlist(rr1 [c("index.treated","index.control")]), ]
#合并匹配后的数据
n <- nrow(zcz_2018)
zcz_index <- bcMatched2[1:n,1]
shz_index <- bcMatched2[(n+1):(2*n),1]
psm_index <- cbind(zcz_index,shz_index)
colnames(psm_index) <- c("注册制股票代码","核准制股票代码")


psm <- replicate(n, list(), simplify = FALSE)
for(i in 1:n){
  zcz_psm <- subset(zcz, id == as.numeric(zcz_index[i,1]))
  #n <- nrow(zcz_psm)
  #shz_psm <- tail(subset(shz_all, id == as.numeric(shz_index[i,1])),n)
  shz_psm <- subset(shz, id == as.numeric(shz_index[i,1]))
  psm[[i]] <- rbind(zcz_psm,shz_psm)
}
combined_psm <- bind_rows(psm) 

write.xlsx(combined_psm, "psm_data.xlsx", sheetName = "Sheet1")
